<?php

class PricetypesServicesController extends AppController {

    var $name = 'PricetypesServices';

    function index() {
        $this->PricetypesService->Pricetype->recursive = 0;
        $pricetypes = $this->PricetypesService->Pricetype->find('all', array('conditions'=>array('Pricetype.deleted'=>0),'order'=>array('Pricetype.name'=>'ASC')));
        $this->set('pricetypes', $pricetypes);
        $services = $this->PricetypesService->Service->find('all', array('order'=>array('Service.name'=>'ASC')));
        $this->set('services', $services);

        if (!empty($this->data)) {

            $array_datos = $this->data['PricetypesService'];

            //empiezo una transaccion
            $this->PricetypesService->query('SET AUTOCOMMIT = 0;');
            $this->PricetypesService->query('START TRANSACTION;');
            $bandera = true; //la uso para ver si algo salio mal
            //borro de la tabla pricetypes_receptions
            if (!$this->PricetypesService->deleteAll(array('1=1'), false, false)) {
                $bandera = false;
            }

            //ahora recorro los datos y voy guardando
            foreach ($services as $service) {

                foreach ($pricetypes as $tipo_precio) {
                    $array_guardar = array();
                    $array_guardar['service_id'] = $service['Service']['id'];
                    $array_guardar['pricetype_id'] = $tipo_precio['Pricetype']['id'];
                    $array_guardar['client_cost'] = $array_datos['client_cost_' .$service['Service']['id'].'_'. $tipo_precio['Pricetype']['id']];

                    $this->PricetypesService->create();
                    if (!$this->PricetypesService->save($array_guardar)) {
                        $bandera = false;
                    }
                }
            }

            if ($bandera) {
                $this->Session->setFlash('Se ha guardado la configuración de los precios');
                $this->PricetypesService->query('COMMIT;');
                $this->PricetypesService->query('SET AUTOCOMMIT = 1;');
                $this->redirect(array('controller' => 'pricetypes_services', 'action' => 'index'));
            } else {
                $this->Session->setFlash('La configuración no ha sido guardada. Por favor, intente nuevamente.');
                $this->PricetypesService->query('ROLLBACK;');
                $this->PricetypesService->query('SET AUTOCOMMIT = 1;');
            }
        } else {
            //si no vino nada, me cargo todo en el $this->data para que se levante solo
            $res = $this->PricetypesService->find('all');
            foreach ($res as $tipo) {
                $this->data['PricetypesService']['client_cost_' . $tipo['PricetypesService']['service_id'] . '_' . $tipo['PricetypesService']['pricetype_id']] = $tipo['PricetypesService']['client_cost'];
            }
        }
    }

}
